<template>
  <div class="pie-container">
    <!-- 切换按钮 -->
    <div class="tab-buttons">
      <button 
        v-for="(tab, index) in tabs" 
        :key="index"
        :class="{ active: activeTab === tab }"
        @click="activeTab = tab"
      >
        {{ tab }}
      </button>
    </div>
    <!-- 饼图容器 -->
    <div ref="chart" class="chart-container"></div>
  </div>
</template>

<script>
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  data() {
    return {
      myEcharts: null,
      activeTab: '女装', // 默认显示女装
      tabs: ['女装', '手机数码', '美妆护肤'], // 三个切换项
      allData: [] // 存储接口返回的完整数据
    };
  },
  methods: {
    async getData() {
      // 调用接口获取数据
      const { data } = await axios.get("http://124.223.9.151:9012/api/hot.json");
      this.allData = data;
      this.renderChart(); // 初始渲染
    },
    renderChart() {
      // 筛选当前tab对应的数据
      const currentData = this.allData.find(item => item.name === this.activeTab);
      if (!currentData) return;

      // 饼图配置
      const option = {
        title: {
          text: `${this.activeTab}热销商品占比`,
          textStyle: { color: '#fff', fontSize: 15 },
          left: 'left'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)' // 显示名称、数值、百分比
        },
        legend: {
          orient: 'horizontal',
          itemWidth: 5,
          itemHeight: 5,
          top:30,
          textStyle: { color: '#fff' },
          data: currentData.children.map(item => item.name)
        },
        series: [
          {
            type: 'pie',
            radius: '60%',
            label:{
              show:false
            },
            data: currentData.children, // 使用对应分类的二级数据
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      this.myEcharts.setOption(option);
    }
  },
  watch: {
    // 监听tab切换，重新渲染图表
    activeTab() {
      this.renderChart();
    }
  },
  mounted() {
    // 初始化图表实例
    this.myEcharts = echarts.init(this.$refs.chart);
    this.getData();

    // 窗口resize时调整图表
    window.addEventListener('resize', () => {
      this.myEcharts && this.myEcharts.resize();
    });
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.myEcharts) {
      this.myEcharts.dispose();
    }
  }
};
</script>

<style scoped>
.pie-container {
  width: 80%;
  padding: 20px;
}
.tab-buttons {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}
.tab-buttons button {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  background: #f0f0f0;
}
.tab-buttons button.active {
  background: #409eff;
  color: white;
}
.chart-container {
  width: 100%;
  height: 400px;
}
</style>